<template>
  <div class="flex">
    <ElUpload v-if="files.length > 0" :before-upload="(f) => editFile(f)" :show-file-list="false" :accept>
      <div class="w50px h50px border border-solid border-blue border-rd mr1 cursor-pointer overflow-hidden hover-box">
        <img :src="files[0].src" :alt="files[0].name" class="w50px"/>
      </div>
    </ElUpload>
    <ElUpload v-else :before-upload="addFile" :show-file-list="false" :accept>
      <div class="flex justify-center items-center w50px h50px border border-solid border-blue border-rd cursor-pointer mr1">+</div>
    </ElUpload>
  </div>
</template>
<script setup lang="ts">
  import { ElUpload, UploadRawFile } from 'element-plus'
  import { ref, watchEffect } from 'vue'
  import { useUploader } from '@/hooks/web/useUploader'
  import { useDownloader } from '@/hooks/web/useDownloader'
  import { getRealName } from '@/utils/fileUtil'
  import VueTypes from 'vue-types'

  const props = defineProps({
    bucket: VueTypes.string.isRequired,
    path: VueTypes.string.def(''),
    multiple: VueTypes.bool.def(false),
    modelValue: VueTypes.string.def(''),
    accept: VueTypes.string.def('')
  })

  const emit = defineEmits(['update:modelValue'])

  const bucket = ref(props.bucket)
  const path = ref(props.path)
  const { files, upload } = useUploader(bucket, path, props.multiple)
  const { getFile } = useDownloader()

  if(props.modelValue) {
    const items = props.modelValue.split(',')
    for(const i in items) {
      const filePath = items[i]
      files.push({ name: getRealName(filePath), filePath })
    }
  }

  const editFile = async (file: UploadRawFile) => {
    const { uid, name, type, size } = file
    files[0] = {
      uid, name, type, size,
      percent: -2,
      file
    }
    await upload()
    return false
  }

  const addFile = async (file: UploadRawFile) => {
    const { uid, name, type, size } = file
    files[0] = {
      uid, name, type, size,
      percent: -2,
      file
    }
    
    await upload()
    return false
  }

  watchEffect(async () => {
    let ret = ''
    for(const i in files) {
      const file = files[i]
      const filePath = file.filePath
      if(filePath) {
        if(ret) ret += ','
        ret += filePath
      }

      if(!file.file && file.filePath) {
        file.file = await getFile(file.filePath, file.name)
      }

      if(file.file) {
        var reader = new FileReader()
        reader.onload = (e) => files[i].src = e.target.result
        reader.readAsDataURL(file.file)
      }
    }
    emit('update:modelValue', ret)
  })

</script>
<style lang="css" scoped> 
  .hover-box:hover {
    background-color: #555; /* 鼠标悬停时的颜色 */
    border: 1px solid red;
    color: white;
    filter: brightness(50%);
  }
</style>
